package cn.christ.com.mobilesafe.service;

import android.accessibilityservice.AccessibilityService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.accessibility.AccessibilityEvent;

import java.util.ArrayList;
import java.util.List;

import cn.christ.com.mobilesafe.constant.Constants;
import cn.christ.com.mobilesafe.modle.AppLockDao;
import cn.christ.com.mobilesafe.view.activity_lockscreen.LockScreenActivity;

public class WatchDogService extends AccessibilityService {

	private AppLockDao mAppLocakDao;
	private List<String> freeContainer = new ArrayList<String>();
	private WatchDogReceiver mWatchDogReceiver;

	@Override
	protected void onServiceConnected() {
		super.onServiceConnected();
		mAppLocakDao = new AppLockDao(getApplicationContext());
		mWatchDogReceiver = new WatchDogReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constants.BoradCastReceiverAction);
		filter.addAction(Intent.ACTION_SCREEN_OFF);
		registerReceiver(mWatchDogReceiver, filter);

		// freeContainer 清空，锁屏的时候，锁屏广播
	}

	@Override
	public void onAccessibilityEvent(AccessibilityEvent event) {
		// 获取当WindowType 发现改变的获取包名
		String packageName = event.getPackageName().toString();
		// 放行
		if (freeContainer.contains(packageName)) {
			return;
		}
		// 判断包名是否在数据库里面
		if (mAppLocakDao.find(packageName)) {
			Intent intent = new Intent(getApplicationContext(), LockScreenActivity.class);
			intent.putExtra("packageName", packageName);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		}
	}

	@Override
	public void onInterrupt() {

	}

	class WatchDogReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (Constants.BoradCastReceiverAction.equals(action)) {
				String packageName = intent.getStringExtra("packageName");
				freeContainer.add(packageName);
			} else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
				freeContainer.clear();
			}

		}

	}

}
